package controllers;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.AutoSiteData;
import data.BlogData;
import data.MessageQueueData;
import debugs.MessageQueueDebug;

import models.AutoSite;
import models.Blog;
import models.MessageQueue;

public class ListMessageQueueServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String gmail = request.getUserPrincipal().getName();
		
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		String siteId = (String) request.getParameter("siteId");
		
		if (siteId == null) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		//Get site info
		AutoSiteData aData = new AutoSiteData();
		AutoSite autoSite = aData.getById(siteId);
		
		//Get blog info
		BlogData blogData = new BlogData();
		Blog blog = blogData.getById(autoSite.getBlogId());
		
		if (blog == null || autoSite == null) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		ArrayList<AutoSite> sites = aData.getByBlogId(autoSite.getBlogId());
		
		ArrayList<MessageQueue> messages = new ArrayList<MessageQueue>();
		
		MessageQueueData mData = new MessageQueueData();
		mData.setLimit(20);
		mData.setPage(page);
		
		//messages = mData.getByAutoSiteId(siteId);
		messages = mData.getAll();
		
		/*for (int i = 0; i < messages.size(); i++) {
			MessageQueueDebug.debug(messages.get(i));
			MessageQueueDebug.debugWeb(messages.get(i), response);
		}*/
		
		request.setAttribute("blog", blog);
		request.setAttribute("sites", sites);
		request.setAttribute("autoSite", autoSite);
		request.setAttribute("messages", messages);
		
		try {
            request.getRequestDispatcher("/pages/list_message_queue.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
}
